<template>
	<view class="body">
		<view class="header" :style="{
        backgroundImage: 'url(' + imgs + ')',
        backgroundRepeat: 'no-repeat',
      }">
			<view class="header_box">
				<view class="header_right">
					<view class="yue">他币余额</view>
					<view class="nums">
						<image :src="getImgUrl('/img/wshing/tab.png')" class="right_img"></image>
						{{ info.balance == undefined || null ? 0 : info.balance }}
					</view>
				</view>
				<view>
					<button class="header_left" @click="ViewDetails">查看明细</button>
				</view>
			</view>
		</view>
		<view class="main">
			<view class="tabichongzhi"> 他币充值 </view>
			<view class="main_center">
				<view class="box" v-for="(item, index) in arr" :key="index"
					@click="selectbtn(item.count, index,item.id)" :style="{
            border: '2rpx solid ' + item.bordercolor,
            background: item.bgcolor,
          }">
					<view class="box_content">
						<image class="box_img" :src="getImgUrl('/img/wshing/tab.png')" mode=""></image>
						{{ item.value }}
					</view>
					<view class="box_count">
						{{ index != 8 ? "￥" + item.count : item.count }}
					</view>
				</view>
			</view>
			<view class="czh"> 充值账户 </view>
			<radio-group @change="rdChange" class="card_radio">
				<!-- 			<view class="zf">
				<view class="zfb">
					<image class="zf_img" :src="getImgUrl('/img/missimg/zhifubao.png')" mode=""></image> <text class="zf_ft">支付宝</text>
				</view>
				<view class="xz">
					<radio value="1" color=" #FF7F22"  />
				</view>
			</view>
			<view class="btn">
				<view class="btn_box">
					
				</view>
			</view> -->
				<view class="zf">
					<view class="zfb">
						<image class="zf_img" :src="getImgUrl('/img/missimg/weixin.png')" mode=""></image>
						<text class="zf_ft">微信</text>
					</view>
					<view class="">
						<radio value="2" color=" #FF7F22" />
					</view>
				</view>
			</radio-group>
			<view class="xieyi">
				<label class="radio">
					<radio value="" color=" #FF7F22" :checked="ischecked" @click="radioChange" />
					<text>阅读并同意   <text @click="rageClick"> 《用户充值协议》</text></text>
				</label>
			</view>
		</view>
		<view class="footer">
			<button class="footer_btn"
			 :style="{backgroundColor:systemInfo.platform != 'ios' ? '#ff7f22' : 'gray'}" 
				@click="recharge">{{systemInfo.platform == 'ios' ? '由于相关规范，iOS功能暂不可用' : '确认充值'}}</button>
		</view>
		<uni-popup ref="inputDialog" type="dialog">
			<!-- 		<uni-popup-dialog ref="inputClose" mode="input" title="充值金额" value="" placeholder="请输入充值金额(￥)"
				@confirm="dialogInputConfirm" @close="dialogClose" ></uni-popup-dialog> -->

			<uni-popup-dialog ref="inputClose" title="充值他币" placeholder="请输入充值金额(￥)" @confirm="dialogInputConfirm"
				@close="dialogClose">
				<uni-easyinput type="text" v-model="money" placeholder="请输入充值金额" @input="moneychange"
					@blur="monchange" />
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		imgBaseUrl
	} from "@/utils/baseUrl.js";
	import {
		currency,
		jsapiPay
	} from "../../../utils/myapi.js";
	import {
		busCoinsppList,
		busCoinscustomize
	} from "../../../utils/OnetoOneaApi";
	let timer = null;
	let count = 0;
	export default {
		data() {
			return {
				imgs: imgBaseUrl + "/img/missimg/tabibeijing.png",
				info: {
					balance: 0,
				}, // 他币信息
				arr: [{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "",
						count: "",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
					{
						value: "自定义",
						count: "最低可充10元",
						iscount: false,
						iscolor: false,
						bacolor: "",
						bordercolor: "#EBEBEB",
					},
				],
				selectarr: [{
						id: "1",
						name: "支付宝",
						isname: false,
					},
					{
						id: "2",
						name: "微信",
						isname: false,
					},
				],
				ischecked: false,
				money: "",
				productId: '',
				wx: '',
				systemInfo: ''
			};
		},
		created() {
			this.getbusCoinsppList();
			//获取是ios设备还是android
			this.systemInfo = wx.getSystemInfoSync()
			console.log(this.systemInfo.platform, 'sys');
		},
		onLoad() {
			this.getInfo();
		},

		methods: {
			//检测值是否为小数
			isDecimal(value) {
				return !Number.isInteger(value); // 利用Number对象的静态属性isInteger进行判断
			},
			// 获取他币信息
			async getbusCoinsppList() {
				const data = await busCoinsppList();
				const result = data.result.records;
				console.log(this.isDecimal(3.4), 'numbers');
				for (let i = 0; i < result.length; i++) {
					if (i <= 7) {
						this.arr[i].value = result[i].number;
						this.arr[i].count = this.isDecimal(result[i].price) == true ? result[i].price + "0" : result[i]
							.price + ".00";
						this.arr[i]['id'] = result[i].id
					}
				}
				console.log(this.arr, 'arr');
			},
			//获取他币余额
			async getInfo() {
				const userinfo = uni.getStorageSync("userInfo");
				const res = await currency(userinfo.id);
				this.info = res.result;
			},
			// 图片渲染
			getImgUrl(image) {
				return imgBaseUrl + image;
			},
			// 选取他币进行充值
			selectbtn(count, index, id) {
				console.log(id, 'id');
				if (count != "最低可充10元") {
					this.money = count;
					this.productId = this.productId == undefined ? '' : id
				} else {
					this.money = "";
				}
				for (let i = 0; i < this.arr.length; i++) {
					if (i == index) {
						this.arr[i].iscolor = true;
						this.arr[i].bordercolor = "#FF7F22";
						this.arr[i].bgcolor = "#FFF5ED";
					} else {
						this.arr[i].iscolor = false;
						this.arr[i].bordercolor = "#EBEBEB";
						this.arr[i].bgcolor = "#F7F7F7";
					}
				}
				if (index == 8) {
					this.$refs.inputDialog.open();
					const index = count.indexOf("￥");
					this.money =
						count == "最低可充10元" ? "" : count.slice(index + 1, count.length);
				}
			},
			async dialogInputConfirm(e) {
				const params = {
					number: this.money,
				};
				const numbers = await busCoinscustomize(params);
				this.productId = numbers.result.id
				this.arr[8]['id'] = numbers.result.id
				this.arr[8].value = numbers.result.number;
				this.arr[8].count = this.isDecimal(numbers.result.price) ? "￥" + numbers.result.price + "0" : "￥" +
					numbers.result.price + ".00";
				this.arr[8].iscolor = true;
				this.arr[8].bordercolor = "#FF7F22";
				this.arr[8].bgcolor = "#FFF5ED";
				this.$refs.inputDialog.close();
			},
			moneychange(e) {
				const inputTypeNum = /[^\d]/g;
				if (!inputTypeNum.test(e)) {
					this.money = e;
					if (e.length > 6) {
						this.money = e.slice(0, 5);
						uni.showToast({
							title: "最多输入五位数!",
							//将值设置为 success 或者直接不用写icon这个参数
							icon: "error",
							//显示持续时间为 2秒
							duration: 500,
						});
					}
				} else {
					this.$nextTick(() => {
						this.money = "";
					});
					uni.showToast({
						title: "输入格式错误!",
						//将值设置为 success 或者直接不用写icon这个参数
						icon: "error",
						//显示持续时间为 2秒
						duration: 2000,
					});
				}
			},
			monchange(e) {
				console.log(e, 'e');
				// this.money = e.detail.value
				if (Number(e.detail.value) % 10 == 0) {
					this.money = e.detail.value
				} else {
					this.money = ''
					uni.showToast({
						title: "输入金额必须为10的倍数!",
						//将值设置为 success 或者直接不用写icon这个参数
						icon: "none",
						//显示持续时间为 2秒
						duration: 2000,
					});
				}
			},
			dialogClose() {
				this.$refs.inputDialog.close();
				this.arr[8].value = "自定义";
				this.arr[8].count = "最低可充10元";
			},
			//选取充值方式
			rdChange(value) {
				console.log(value);
				this.wx = value.detail.value
			},
			//选择用户充值协议
			radioChange(e) {
				this.ischecked = !this.ischecked;
			},
			//查看明细
			ViewDetails() {
				uni.navigateTo({
					url: "../tabidetails/tabidetails",
				});
			},
			async recharge() {
				console.log(this.wx, 'cccc');
				if (this.systemInfo.platform == 'ios') {
					uni.showToast({
						icon: 'none',
						title: 'iOS功能暂不可用!',
						duration: 2000
					});
				} else {
					if (this.wx == 2 && this.ischecked == true && this.money != '') {
						let _this = this;
						const res = await jsapiPay(this.productId)
						// const paySign = this.generatePaySign(payParams);
						// 仅作为示例，非真实参数信息。
						uni.requestPayment({
							provider: 'wxpay', //服务提供商
							timeStamp: res.result.timeStampstring, // 时间戳
							nonceStr: res.result.nonceStr, //随机字符串
							package: `prepay_id=${res.result.prepay_id}`, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
							prepay_id: res.result.orderNo, //订单编号
							signType: res.result.signType, //签名类型，默认为MD5，支持HMAC-SHA256和MD5。注意此处需与统一下单的签名类型一致
							paySign: res.result.sign, //签名 
							success: async function(res) {
								console.log('success:' + JSON.stringify(res));
								clearInterval(timer)
								timer = setInterval(() => {
									count++
									if (count < 6) {
										_this.getInfo();

									}
								}, 1000)
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: '请将信息填写完整!',
							duration: 2000
						});
					}
				}


			},
			generatePaySign(params) {
				let keys = Object.keys(params).sort();
				let str = '';

				for (let i = 0; i < keys.length; i++) {
					str += `${keys[i]}=${encodeURIComponent(params[keys[i]])}&`;
				}

				return md5(`${str}key=yourKey`); // yourKey为自定义密钥
			},
			//跳转到用户充值协议
			rageClick(){
				uni.navigateTo({
					url:'../../pages/Recharge/Recharge',
				})
			}
		},
	};
</script>

<style lang="less" scoped>
	.body {
		display: flex;
		justify-content: space-between;
		flex-direction: column;
		align-items: center;

		//   height: 100vh;
		//   padding-bottom: 100rpx;
		.header {
			width: 90%;
			height: 212rpx;
			background: linear-gradient(270deg, #ff7f22 0%, #ffa725 100%);
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			opacity: 1;

			.header_box {
				padding: 30rpx 20rpx 20rpx 33rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.header_right {
					.yue {
						font-size: 26rpx;
						font-family: PingFang SC-Medium, PingFang SC;
						font-weight: 500;
						color: #ffffff;
					}

					.nums {
						font-size: 72rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #ffffff;
					}

					.right_img {
						width: 60rpx;
						height: 60rpx;
						vertical-align: middle;
					}
				}

				.header_left {
					width: 184rpx;
					height: 74rpx;
					line-height: 74rpx;
					border-radius: 24rpx 24rpx 24rpx 24rpx;
					opacity: 1;
					border: 2rpx solid #ffffff;
					background: #ff7f22;
					color: #ffffff;
					font-size: 30rpx;
					font-family: PingFang SC-Bold, PingFang SC;
				}
			}
		}

		.main {
			width: 90%;
			// height: 69vh;
			// background: palevioletred;
			margin-top: 30rpx;

			.tabichongzhi {
				font-size: 36rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #222229;
			}

			.main_center {
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
				padding-top: 10rpx;

				// height: 35vh;
				.box {
					width: 210rpx;
					height: 160rpx;
					background: #f7f7f7;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					opacity: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					margin-top: 18rpx;

					.box_content {
						font-size: 40rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #333333;

						.box_img {
							width: 36rpx;
							height: 36rpx;
							vertical-align: middle;
						}
					}

					.box_count {
						font-size: 26rpx;
						font-family: PingFang SC-Medium, PingFang SC;
						font-weight: 500;
						color: #666666;
					}
				}
			}

			.czh {
				font-size: 34rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #333333;
				padding: 62rpx 0 20rpx 0;
			}

			.zf {
				display: flex;
				justify-content: space-between;
				padding: 30rpx 0 40rpx 0;

				.zf_img {
					width: 48rpx;
					height: 48rpx;
					vertical-align: middle;
				}

				.zf_ft {
					margin-left: 20rpx;
				}
			}

			.btn {
				display: flex;
				justify-content: flex-end;

				.btn_box {
					width: 80%;
					height: 2rpx;
					background: #ebebeb;
					border-radius: 0rpx 0rpx 0rpx 0rpx;
					opacity: 1;
				}
			}

			.xieyi {
				margin-top: 77rpx;
				display: flex;
				justify-content: center;
				font-size: 26rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #999999;
			}
		}

		.footer {
			width: 90%;
			height: 200rpx;

			// background-color: pink;
			.footer_btn {
				background: #ff7f22;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				color: #ffffff;
				margin-top: 30rpx;
			}
		}
	}
</style>